//
//  UIKit+.swift
//  suda
//
//  Created by youai on 2019/7/11.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import UIKit

extension UIView {
    func debugColor(){
        self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.5)
    }
    
    @discardableResult
    func cornerRadius(_ value:CGFloat)->UIView{
        self.layer.cornerRadius = value
        return self
    }
}


extension UIColor{
    convenience init(hex:Int,alpha:CGFloat = 1){
        let blue:CGFloat = CGFloat(hex % 256)
        let green:CGFloat = CGFloat((hex / 256) % 256)
        let red:CGFloat = CGFloat(( hex / 256 / 256 ) % 256)
        self.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)
    }
}

extension UIImage{
    func resizeImage(targetSize: CGSize) -> UIImage? {
        let size = self.size
        
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
        
        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = .init(width:size.width * heightRatio, height:size.height * heightRatio)
        } else {
            newSize = .init(width:size.width * widthRatio,  height:size.height * widthRatio)
        }
        
        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x:0, y:0, width:newSize.width, height:newSize.height)
        
        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage
    }
    
    //颜色转图片
    class func createImageFrom(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? {
        let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image ?? nil
    }
}

class TextField : UITextField {
    ///可放大点击区域
    var hitEdgInsets : UIEdgeInsets = .zero
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let expandedBounds = bounds.inset(by: hitEdgInsets)
        return expandedBounds.contains(point)
    }
    
    func isEmpty()->Bool{
        return self.text == nil || self.text?.count ?? 0 == 0
    }
    
    var doubleValue : Double? { get {
        guard let t = text else {
            return nil
        }
        return Double(t)
        }}
    func textOrNil()->String? {
        if isEmpty() { return nil }
        return text
    }
}

///拥有渐变背景色的UIView
class UIViewWithGradientLayer : UIView {
    //背景图层（暂定只需要一个图层）
    var customLayer : CALayer? = nil
    //在自动布局完成后，调整背景图层的位置
    override func layoutSubviews() {
        super.layoutSubviews()
        customLayer?.frame = self.bounds
    }
    //插入背景图层
    func insertBackgroundLayer(_ layer:CALayer){
        self.layer.insertSublayer(layer, at: 0)
        self.customLayer = layer
    }
    //绘制渐变背景图层
    @discardableResult
    func drawGradientLayer(
        color1:CGColor,color2:CGColor,
        x1:CGFloat,y1:CGFloat,x2:CGFloat,y2:CGFloat
        )->CAGradientLayer{
        let bgLayer = CAGradientLayer()
        bgLayer.colors = [color1, color2]
        bgLayer.locations = [0, 1]
        bgLayer.startPoint = CGPoint(x: x1, y: y1)
        bgLayer.endPoint = CGPoint(x: x2, y: y2)
        if self.layer.cornerRadius > 0 {
            bgLayer.cornerRadius = self.layer.cornerRadius
        }
        self.insertBackgroundLayer(bgLayer)
        return bgLayer
    }
}

///DispatchQueue.main.async 的快捷方式
func mainQueueAsync(_ closure:@escaping ()->Void){
    if !Thread.current.isMainThread {
        DispatchQueue.main.async(execute:closure)
    }else{
        closure()
    }
}

extension UIViewController {
    
    //有主线程同步的pushViewController
    @objc func pushViewController(_ vc:UIViewController){
        if !Thread.current.isMainThread {
            mainQueueAsync {
                self.pushViewController(vc)
            }
            return
        }
        if let nav = self.navigationController {
            nav.pushViewController(vc, animated: true)
        }else{
            present(vc, animated: true)
        }
    }
    
    @objc func pushViewControllerWithAnimated(_ vc:UIViewController,animated:Bool=false){
        if !Thread.current.isMainThread {
            mainQueueAsync {
                self.pushViewControllerWithAnimated(vc, animated: animated)
            }
            return
        }
        if let nav = self.navigationController {
            nav.pushViewController(vc, animated: animated)
        }else{
            present(vc, animated: animated)
        }
    }
    
    ///有主线程同步的popViewController
    @objc func popViewController(){
        if !Thread.current.isMainThread {
            mainQueueAsync {
                self._popViewController(animated: true)
            }
            return
        }
        _popViewController(animated: true)
    }
    
    ///无主线程同步的popViewController
    @objc func _popViewController(animated:Bool){
        if let nv = self.navigationController ?? self.tabBarController?.navigationController {
            nv.popViewController(animated: animated)
        }else{
            self.dismiss(animated: animated)
        }
    }
    
    ///有主线程同步的popViewController
    ///1时自己，2为上一层，w如此类推
    @objc func popViewController(animated: Bool=true,vCount:Int){
        if !Thread.current.isMainThread {
            mainQueueAsync {
                self._popViewController(animated: animated, vCount: vCount)
            }
            return
        }
        _popViewController(animated: animated, vCount: vCount)
    }
    
    ///无主线程同步的popViewController
    @objc func _popViewController(animated:Bool, vCount:Int = 2){
        if (self.navigationController ?? self.tabBarController?.navigationController) != nil {
            let vcCount = self.navigationController?.viewControllers.count
            self.navigationController?.popToViewController((self.navigationController?.viewControllers[vcCount! - vCount])!, animated: animated)
        }else{
            self.dismiss(animated: animated)
        }
    }
    
    @objc func popViewControllerToTop(animated:Bool = true){
        if (self.navigationController ?? self.tabBarController?.navigationController) != nil {
            self.navigationController?.popToViewController((self.navigationController?.viewControllers[0])!, animated: animated)
        }else{
            self.dismiss(animated: animated)
        }
    }
    
    ///获取指定ViewController的顶部VC
    static func _topMostController(vc:UIViewController)->UIViewController? {
        var topController:UIViewController = vc
        while topController.presentedViewController != nil {
            topController = topController.presentedViewController!
        }
        
        if topController.isKind(of: UINavigationController.self){
            let visible = (topController as! UINavigationController).visibleViewController
            if visible != nil  {
                topController = visible!
            }
        }
        return (topController != vc) ? topController : nil
    }
    
    ///获取目前APP最顶部的ViewController
    static func topMostController()->UIViewController? {
        if var topController = UIApplication.shared.keyWindow?.rootViewController {
            var next:UIViewController? = nil;
            while(true){
                next = _topMostController(vc: topController)
                if next == nil {
                    break
                }
                topController = next!
            }
            return topController;
        }else{
            return nil
        }
    }
    
    func showAlert(content:String,title:String = "温馨提醒"){
        if !Thread.current.isMainThread{
            mainQueueAsync {
                self.showAlert(content:content,title:title)
            }
            return
        }
        let alert = UIAlertController(title: title, message: content, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "确定", style: .default)
        alert.addAction(defaultAction)
        self.present(alert, animated: true)
    }
    
    static func showAlert(content:String,title:String = "温馨提醒"){
        if !Thread.current.isMainThread{
            mainQueueAsync {
                showAlert(content:content,title:title)
            }
            return
        }
        topMostController()?.showAlert(content: content,title:title)
    }
    
    func showConfirm(content:String,title:String = "温馨提醒",onSure : @escaping EMPTY_CLOSURE){
        let alertController = UIAlertController(title: title,message: content, preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .default, handler: {
            action in
            onSure()
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

let SCREEN_WIDTH : CGFloat = {
    return UIScreen.main.bounds.width
}()

extension UIButton {
    func alignTextUnderImage(spacing: CGFloat = 6.0) {
        guard let image = imageView?.image, let label = titleLabel,
            let string = label.text else { return }
        
        titleEdgeInsets = UIEdgeInsets(top: spacing, left: -image.size.width, bottom: -image.size.height, right: 0.0)
        let titleSize = string.size(withAttributes: [NSAttributedString.Key.font: label.font!])
        imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
    }
}


let DateFormatter_YYYY_MM_DD : DateFormatter = {
    let df = DateFormatter()
    df.dateFormat = "yyyy-MM-dd"
    return df
}()

//让textfield变成日期选择框
class DatePickerForTextField : UIDatePicker,UIGestureRecognizerDelegate{
    var textField : UITextField? = nil
    var dateFormatter = DateFormatter()
    func setTextField(_ textField: UITextField, type: UIDatePicker.Mode = .date) {
        self.textField = textField
        self.datePickerMode = type
        switch type {
        case .time:
            dateFormatter.dateFormat = "HH:mm:ss"
        case .date:
            dateFormatter.dateFormat = "yyyy-MM-dd"
        case .dateAndTime:
            dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        case .countDownTimer:
            dateFormatter.dateFormat = "HH:mm"
        @unknown default:
            break
        }
        self.addTarget(self, action: #selector(onDatePickerValueChanged(datePicker:)), for: .valueChanged)
        let tap = UITapGestureRecognizer(target: self, action: #selector(onDatePickerTap))
        tap.delegate = self
        self.addGestureRecognizer(tap)
        textField.inputView = self
    }
    private func _setTextFieldText(){
//        print("\(String(describing: dateFormatter.dateFormat))")
        textField?.text = dateFormatter.string(from: self.date)
    }
    @objc func onDatePickerValueChanged(datePicker:UIDatePicker){
        _setTextFieldText()
    }
    @objc func onDatePickerTap(){
        _setTextFieldText()
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool{
        return true
    }
    var value : String? { get {
        let text = textField?.text
        if text == nil || text!.count == 0 {
            return text
        }
        return text
        }}
}

//解决 UIAlertController 约束错误信息
extension UIAlertController {
    func pruneNegativeWidthConstraints() {
        for subView in self.view.subviews {
            for constraint in subView.constraints where
                constraint.debugDescription.contains("width == - 16") {
//                    print(subView)
                subView.removeConstraint(constraint)
            }
        }
    }
}

extension UILabel {
    //设置气泡文字
    func setBubbleNumber(_ number:Int){
        self.text = nil
        self.attributedText = nil
        let color = self.textColor
        let attrString = NSMutableAttributedString(string: "  \(number)  ")
        let textFont = self.font ?? UIFont.systemFont(ofSize: 8)
//                let attr: [NSAttributedString.Key : Any] = [.font: textFont ,.foregroundColor: color]
//                attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        let spaceRate : (CGFloat) = (number == 1) ? 0.65 :( (number <= 9) ? 0.55 : 0.5 )
        let spaceFont = UIFont.systemFont(ofSize: textFont.pointSize*spaceRate)
        
        let strSubAttr1: [NSMutableAttributedString.Key: Any] = [.font: spaceFont,.foregroundColor: color as Any, .kern:0]
        attrString.addAttributes(strSubAttr1, range: NSRange(location: 0, length: 2))
        
        let strSubAttr2: [NSMutableAttributedString.Key: Any] = [.font: textFont,.foregroundColor: color as Any, .kern:-0.5]
        attrString.addAttributes(strSubAttr2, range: NSRange(location: 2, length: attrString.length-4))

        let strSubAttr3: [NSMutableAttributedString.Key: Any] = [.font: spaceFont,.foregroundColor: color as Any, .kern:0]
        attrString.addAttributes(strSubAttr3, range: NSRange(location: attrString.length-2, length: 2))

        self.attributedText = attrString
    }
}

extension UIPageControl {

    func customPageControl(dotBorderColor:UIColor, dotBorderWidth:CGFloat) {
        for (_, dotView) in self.subviews.enumerated() {
                dotView.layer.cornerRadius = dotView.frame.size.height / 2
                dotView.layer.borderColor = dotBorderColor.cgColor
                dotView.layer.borderWidth = dotBorderWidth
        }
    }

}
